package com.radioapp.liaoliaobao.module.user;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.platform.comapi.map.G;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.gms.common.api.Releasable;
import com.jaydenxiao.common.base.BaseRiggerFragment;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.sharepref.SharePref;
import com.jaydenxiao.common.url.BaseConstant;
import com.jkb.fragment.rigger.rigger.Rigger;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.radioapp.liaoliaobao.BuildConfig;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.app.GlideImageLoader;
import com.radioapp.liaoliaobao.bean.MediaTypeBean;
import com.radioapp.liaoliaobao.bean.lite.ChatUser;
import com.radioapp.liaoliaobao.bean.user.LoginBean;
import com.radioapp.liaoliaobao.bean.user.PhotoImageBean;
import com.radioapp.liaoliaobao.bean.user.UpdateMediaBean;
import com.radioapp.liaoliaobao.bean.user.UserBean;
import com.radioapp.liaoliaobao.constant.Constants;
import com.radioapp.liaoliaobao.constant.Global;
import com.radioapp.liaoliaobao.module.photoImage.PhotoImageFragment;
import com.radioapp.liaoliaobao.module.user.auth.AuthIDFragment;
import com.radioapp.liaoliaobao.module.user.blacklist.BlackListFragment;
import com.radioapp.liaoliaobao.module.user.customer.CustomerFragment;
import com.radioapp.liaoliaobao.module.user.login.LoginFragment;
import com.radioapp.liaoliaobao.module.user.my_radio.MyRadioFragment;
import com.radioapp.liaoliaobao.module.user.mylike.MyLikeFragment;
import com.radioapp.liaoliaobao.module.user.privacy.PrivacySettingFragment;
import com.radioapp.liaoliaobao.module.user.setting.SettingFragment;
import com.radioapp.liaoliaobao.module.user.wallet.WalletFragment;
import com.radioapp.liaoliaobao.uihelper.UiHelper;
import com.radioapp.liaoliaobao.utils.EaseUIUtils;
import com.radioapp.liaoliaobao.utils.IsVipUtil;
import com.radioapp.liaoliaobao.utils.MoneyExchange;
import com.radioapp.liaoliaobao.utils.dialog.AlertDialogutils;
import com.radioapp.liaoliaobao.utils.timePicker.SelectImageUtils;
import com.radioapp.liaoliaobao.utils.timePicker.TimePickerOneUtil;
import com.radioapp.liaoliaobao.view.NiceImageView;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.LogUtils;

/**
 * 功能： 用户
 * 描述
 * Created by yue on 2019-07-03
 */
public class UserFragment extends BaseRiggerFragment<UserView, UserPresenter> implements
        UserView, BaseQuickAdapter.OnItemClickListener {

    public static final int UPLOADMEDIAREQUSET = 12;

    @BindView(R.id.user_iv_avatar)
    NiceImageView ivAvatar;
    @BindView(R.id.tv_nickName)
    TextView tvNickName;
    @BindView(R.id.tv_auto)
    TextView tvAuto;
    @BindView(R.id.tv_user_wallet)
    TextView tvUserWallet;
    @BindView(R.id.rl_private_setting)
    RelativeLayout rlPrivateSetting;
    @BindView(R.id.rl_evaluation)
    RelativeLayout rlEvaluation;
    @BindView(R.id.rl_dynamic)
    RelativeLayout rlDynamic;
    @BindView(R.id.tv_visitor)
    TextView tvVisitor;
    @BindView(R.id.tv_setting)
    TextView tvSetting;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_upload_image)
    TextView tvUploadImage;
    @BindView(R.id.user_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rl_wallet)
    RelativeLayout rlWallet;
    @BindView(R.id.rl_member)
    RelativeLayout rlMember;
    @BindView(R.id.tv_member)
    TextView tvMember;
    @BindView(R.id.tv_broadcase_content)
    TextView tvBroadCase_content;


    UserBean userBean;


    private List<LocalMedia> selectList = new ArrayList<>();

    private int mediaType; //图片类型

    private UserMediaAdapter userMediaAdapter;
    private boolean isSelectPhoto;


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_user;
    }


    @Override
    protected void initView() {
        initToolbar("我的", false, false, null);
        tvUploadImage.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvVersion.setText(BuildConfig.VERSION_NAME);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 4));
        userMediaAdapter = new UserMediaAdapter();
        recyclerView.setAdapter(userMediaAdapter);
        userMediaAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<UpdateMediaBean> list = adapter.getData();
                ArrayList<PhotoImageBean> photoImageBeans = new ArrayList<>();
                for (UpdateMediaBean userMedia : list) {
                    PhotoImageBean photoImageBean = new PhotoImageBean();
                    photoImageBean.setId(userMedia.getId());
                    photoImageBean.setIs_once(userMedia.getIs_once());
                    photoImageBean.setPrice(userMedia.getPrice());
                    photoImageBean.setFile_size(userMedia.getFile_size());
                    photoImageBean.setType(userMedia.getType());
                    photoImageBean.setResource_url(userMedia.getResource_url());
                    photoImageBean.setMime_type(userMedia.getMime_type());
                    photoImageBeans.add(photoImageBean);
                }
                //图片列表
                Rigger.getRigger(mActivity).startFragment(PhotoImageFragment.newInterface(photoImageBeans, position, true));
            }
        });

    }

    @Override
    public void tokenInvalidRefresh() {
        //  mPresenter.getUserInfo();
        mPresenter.getUserInfo();
    }


    @Override
    public void onFragmentResume() {
        super.onFragmentResume();
        if (!isSelectPhoto) {
            mPresenter.getUserInfo();
        }

        if (SharePref.getInt(Constants.REGISTER_MEETING, 0) == 1) {
            tvBroadCase_content.setVisibility(View.VISIBLE);
        } else {
            tvBroadCase_content.setVisibility(View.GONE);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void getUserInfo(UserBean userBean) {
        this.userBean = userBean;
        LoginBean loginBean = Global.getLoginBean();
        loginBean.setGender(userBean.getGender());
        loginBean.setInvite_code(userBean.getInvite_code());
        loginBean.setVip_ended_at(userBean.getVip_ended_at());
        //保存用户信息
        Global.saveUserInfo(userBean);
        SharePref.saveInt(Constants.PRIVACY_STATUS, userBean.getPrivacy_status());

        tvNickName.setText(userBean.getNickname()); //昵称
        //头像
        GlideImageLoader.displayImage(mActivity, BaseConstant.IMAGEURL + userBean.getAvatar(), ivAvatar);
        //钱包
        tvUserWallet.setText(MoneyExchange.exchange(userBean.getCash()));
        //历史访客
        tvVisitor.setText("有" + userBean.getHistory_visitors() + "个人看过我");

        if (userBean.getGender() == 1) {
            rlWallet.setVisibility(View.INVISIBLE);
            tvAuto.setVisibility(View.INVISIBLE);
            rlMember.setVisibility(View.VISIBLE);
            if (IsVipUtil.isVip(userBean.getVip_ended_at())) {
                tvMember.setText("已开通会员");
            } else {
                tvMember.setText("升级会员尊享会员特权");
            }
        } else if (userBean.getGender() == 2) {
            rlWallet.setVisibility(View.VISIBLE);
            rlMember.setVisibility(View.GONE);
            tvAuto.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(userBean.getVerified_at())) {
                if (userBean.getIn_certification() == 1) {
                    tvAuto.setText("认证审核中");
                } else {
                    tvAuto.setText("未认证");
                }
            } else {
                tvAuto.setText("已认证");
            }
        }


        mPresenter.updateMediaList(userBean.getId());
        if (userBean.getGender() == 1) {

        }

        //保存数据
        ChatUser chatUser = new ChatUser(userBean.getId()
                , userBean.getNickname(), BaseConstant.IMAGEURL + userBean.getAvatar());

    }


    /**
     * 退出帐号
     */
    @Override
    public void loginOutSuccess() {
        UiHelper.showLoginFragment(mActivity);
        //环信退出
        EaseUIUtils.loginOut();
        //清除数据
        SharePref.clear();
    }

    @Override
    public void generateCodeSuccess() {
        ToastUitl.showLong("提交申请成功");

    }

    @Override
    public void avatarUrl(String avatar_url) {
        GlideImageLoader.displayImage(mActivity, BaseConstant.IMAGEURL + avatar_url, ivAvatar);
    }


    @Override
    public void updateMedia(List<UpdateMediaBean> updateMediaBeans) {
        userMediaAdapter.setNewData(updateMediaBeans);
    }

    @OnClick({R.id.user_iv_avatar, R.id.tv_auto, R.id.tv_upload_image, R.id.tv_info_material, R.id.rl_wallet, R.id.rl_member, R.id.rl_private_setting, R.id.rl_evaluation,
            R.id.rl_broadcase, R.id.rl_dynamic, R.id.rl_like, R.id.rl_blacklist, R.id.rl_visitor,
            R.id.rl_setting, R.id.rl_invitation_code, R.id.rl_customer, R.id.rl_version, R.id.rl_out_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_iv_avatar:
                SelectImageUtils.showALlImage(this, selectList, 1, PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tv_auto: //认证
                if (TextUtils.isEmpty(userBean.getVerified_at()) && userBean.getIn_certification() == 0) {
                    UiHelper.showAuthIDFragment(mActivity);
                }
                break;
            case R.id.tv_upload_image:
                isSelectPhoto = true;
                new TimePickerOneUtil<MediaTypeBean>().showPickerView(mActivity, "照片类型", Constants.getMediaTypes(userBean.getGender()),
                        new TimePickerOneUtil.SelectListener<MediaTypeBean>() {
                            @Override
                            public void onSelected(MediaTypeBean mediaTypeBean) {
                                mediaType = mediaTypeBean.id;
                                SelectImageUtils.showALlImage(UserFragment.this, new ArrayList<>(), 9, UPLOADMEDIAREQUSET);
                            }
                        });

                break;
            case R.id.tv_info_material: //编辑资料
                UiHelper.showMaterialActivity(mActivity, 0);
                break;
            case R.id.rl_wallet: //钱包
                UiHelper.showWalletFragment(mActivity);
                break;
            case R.id.rl_member: //会员
                UiHelper.showMemberFragment(mActivity, userBean.getVip_ended_at());
                break;
            case R.id.rl_private_setting: //隐私设置
                UiHelper.showPrivacySettingFragment(mActivity);
                break;
            case R.id.rl_evaluation: //我的评价
                break;
            case R.id.rl_broadcase:  //我 的广播
                UiHelper.showMyRadioFragment(mActivity);
                break;
            case R.id.rl_dynamic:  //我的动态
                break;
            case R.id.rl_like: //我喜欢的
                UiHelper.showMyLikeFragment(mActivity);
                break;
            case R.id.rl_blacklist: //我的黑名单
                UiHelper.showBlackListFragment(mActivity);
                break;
            case R.id.rl_visitor:  //历史访客
                break;
            case R.id.rl_setting:  //设置

                UiHelper.showSettingFragment(mActivity);
                break;
            case R.id.rl_invitation_code:  //邀请码
                AlertDialogutils.createDialog(mActivity, "确定帮朋友申请邀请码吗？", "确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.generateCode();
                    }
                });
                break;
            case R.id.rl_customer:  //客服
                UiHelper.showCustomerFragment(mActivity);
                break;
            case R.id.rl_version:  //版本
                break;
            case R.id.rl_out_login:  //退出登录，
                AlertDialogutils.createDialog(mActivity, "确定退出吗？", "确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.loginOut();
                    }
                });
                break;
            default:
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList.get(0) != null) {
                        String path = getpathImage(selectList.get(0));
                        mPresenter.uploadAcatar(new File(path));
                    }
                    break;
                case UPLOADMEDIAREQUSET:
                    isSelectPhoto = false;
                    List<LocalMedia> selectMediaList = PictureSelector.obtainMultipleResult(data);
                    List<String> paths = new ArrayList<>();
                    if (selectMediaList != null && selectMediaList.size() > 0) {
                        for (LocalMedia media : selectMediaList) {
                            paths.add(getpathImage(media));
                        }
                    }
                    mPresenter.uploadResource(paths, mediaType, userBean.getId());
                    break;
            }
        }
    }

    /**
     * 获取图片，
     *
     * @param model
     * @return
     */
    public String getpathImage(LocalMedia model) {
        String path = "";
        if (model.isCut() && !model.isCompressed()) {
            // 裁剪过
            path = model.getCutPath();
        } else if (model.isCompressed() || (model.isCut() && model.isCompressed())) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = model.getCompressPath();
        } else {
            // 原图
            path = model.getPath();
        }
        return path;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List<UpdateMediaBean> list = adapter.getData();
        ArrayList<PhotoImageBean> photoImageBeans = new ArrayList<>();
        for (UpdateMediaBean userMedia : list) {
            PhotoImageBean photoImageBean = new PhotoImageBean();
            photoImageBean.setId(userMedia.getId());
            photoImageBean.setIs_once(userMedia.getIs_once());
            photoImageBean.setPrice(userMedia.getPrice());
            photoImageBean.setFile_size(userMedia.getFile_size());
            photoImageBean.setType(userMedia.getType());
            photoImageBean.setResource_url(userMedia.getResource_url());
            photoImageBean.setMime_type(userMedia.getMime_type());
            photoImageBeans.add(photoImageBean);
        }
        //图片列表
        Rigger.getRigger(mActivity).startFragment(PhotoImageFragment.newInterface(photoImageBeans, position, false));
    }
}
